package com.doctor.windflower_doctor.activity;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.ResponseEntity;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.doctor.windflower_doctor.R;
import com.doctor.windflower_doctor.adapter.OnLineTalkWithAdapter;
import com.doctor.windflower_doctor.db.SharedPreferencesDB;
import com.doctor.windflower_doctor.delegate.WindflowerDelegate;
import com.doctor.windflower_doctor.entity.DialogueBeen;
import com.doctor.windflower_doctor.entity.Msg;
import com.doctor.windflower_doctor.http.callback.HttpSpringCallBack;
import com.doctor.windflower_doctor.http.parser.impl.JsonParser;
import com.doctor.windflower_doctor.http.request.HttpRequest;
import com.doctor.windflower_doctor.pop.SureCanclePop;
import com.doctor.windflower_doctor.service.DialogueService;
import com.doctor.windflower_doctor.util.AudioRecorder;
import com.doctor.windflower_doctor.util.Constent;
import com.doctor.windflower_doctor.util.RecordThread;
import com.doctor.windflower_doctor.util.StringUtil;
import com.doctor.windflower_doctor.view.PullToCustomListView;
import com.lidroid.xutils.util.LogUtils;

/**
 * <p>
 * 功能 问答列表页
 * </p>
 * 
 * <p>
 * Copyright 北京亚普拓信息咨询服务有限公司 2014 All right reserved.
 * </p>
 * 
 * @author 皮勉 时间 2014年10月13日 下午1:23:50
 * @version 1.0 </br> 最后修改人 无
 * 
 */
public class QuestionOnLineActivity extends BaseActivity implements OnClickListener, Constent {
	private PullToCustomListView custom_list;
	private ListView listView;
	private OnLineTalkWithAdapter onLineTalkWithAdapter;
	private TextView textView, time_text;
	private ImageButton back_btn;
	private ImageButton orenge_btn;
	private ImageView soft_input_img;
	private ImageView voice_input_img;
	private TextView send_btn, todo_text;
	private ImageView voice_img;
	private EditText publish_text;
	private RelativeLayout bottom_layout, close, card, voice_layout, report;
	private LinearLayout select_dialog;
	private static int MAX_TIME = 60; // 最长录制时间，单位秒，0为无时间限制
	private static int MIX_TIME = 2; // 最短录制时间，单位秒，0为无时间限制，建议设为1
	private static int RECORD_NO = 0; // 不在录音
	private static int RECORD_ING = 1; // 正在录音
	private static int RECODE_ED = 2; // 完成录音
	private static int RECODE_CANCLE = 3; // 完成录音
	private static int RECODE_STATE = 0; // 录音的状态
	private static float recodeTime = 0.0f; // 录音的时间
	private static double voiceValue = 0.0; // 麦克风获取的音量值
	private ImageView dialog_img;
	private Dialog dialog, dialogCancle;
	private AudioRecorder mr;
	private Thread recordThread;
	private float startY = 0;
	private float endY = 0;
	private Resources resources;
	private String userId;
	private String questionId;
	private String name;
	private int replyStatus;
	private UpLoadImageAsyn imageAsyn;
	private LinearLayout full_screem;
	private PopupWindow pop_noty;
	private LinearLayout more_noty;
	private RelativeLayout question_layout;
	public static final String ACTION = "com.doctor.windflower_doctor.activity.QuestionOnLineActivity";
	public static final String DIALOG_DOCTOR_EVALUATE = "com.doctor.windflower_doctor.activity.QuestionOnLineActivity.dialog_doctor_evaluste";
	private Handler popupHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				initPop(question_layout);
				SharedPreferencesDB.getInstance(QuestionOnLineActivity.this).setIsFirst(false);
				break;
			}
		}

	};

	@Override
	protected void getSaveData(Bundle savedInstanceState) {

		// TODO Auto-generated method stub

	}

	@Override
	protected void processLogic() {

		// TODO Auto-generated method stub

	}

	@Override
	protected void setListener() {
		onLineTalkWithAdapter = new OnLineTalkWithAdapter(QuestionOnLineActivity.this, userId);
		listView.setAdapter(onLineTalkWithAdapter);
		back_btn.setOnClickListener(this);
		orenge_btn.setOnClickListener(this);
		voice_input_img.setOnClickListener(this);
		soft_input_img.setOnClickListener(this);
		send_btn.setOnClickListener(this);
		select_dialog.setOnClickListener(this);
		close.setOnClickListener(this);
		card.setOnClickListener(this);
		report.setOnClickListener(this);
		publish_text.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				select_dialog.setVisibility(View.GONE);
				return false;
			}
		});
		voice_img.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				select_dialog.setVisibility(View.GONE);
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					voice_img.setSelected(true);
					todo_text.setText("松开手指  取消发送");
					startY = event.getY();
					if (RECODE_STATE != RECORD_ING) {
						scanOldFile();
						mr = new AudioRecorder("voice");
						RECODE_STATE = RECORD_ING;
						showVoiceDialog();
						try {
							mr.start();
						} catch (Exception e) {
							e.printStackTrace();
						}
						mythread();
					}

					break;
				case MotionEvent.ACTION_UP:
					voice_img.setSelected(false);
					todo_text.setText("按住说话");
					endY = event.getY();
					if (RECODE_STATE == RECODE_CANCLE) {
						if (dialogCancle != null && dialogCancle.isShowing()) {
							dialogCancle.dismiss();
						}
					}
					if (RECODE_STATE == RECORD_ING) {
						RECODE_STATE = RECODE_ED;
						LogUtils.e("==================ACTION_UP==================");
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
						if (dialogCancle != null && dialogCancle.isShowing()) {
							dialogCancle.dismiss();
						}
						try {
							// rThread.pause();
							mr.stop();
							voiceValue = 0.0;
						} catch (Exception e) {
							e.printStackTrace();
						}

						if (recodeTime < MIX_TIME || RECODE_STATE == RECODE_CANCLE) {
							showWarnToast();
							// record.setText("按住开始录音");
							RECODE_STATE = RECORD_NO;
						} else {
							imageAsyn = new UpLoadImageAsyn();
							imageAsyn.execute();
							// record.setText("录音完成!点击重新录音");
							// luyin_txt.setText("录音时间：" + ((int)
							// recodeTime));
							// luyin_path.setText("文件路径：" + getAmrPath());
						}
					}

					break;
				case MotionEvent.ACTION_MOVE:
					endY = event.getY();
					LogUtils.e("==================ACTION_MOVE==================");
					if (Math.abs(startY - endY) > 100) {
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
						if (dialogCancle == null || !dialogCancle.isShowing()) {
							RECODE_STATE = RECODE_CANCLE;
							showVoiceCancleDialog();
						}
					}
				}
				return false;
			}
		});
		// full_screem.setOnTouchListener(new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View arg0, MotionEvent arg1) {
		// if (select_dialog.getVisibility() == View.VISIBLE)
		// select_dialog.setVisibility(View.GONE);
		// return false;
		// }
		// });
	}

	@Override
	protected void findViews() {
		resources = this.getResources();
		textView = (TextView) findViewById(R.id.textView);
		Bundle bundle = getIntent().getExtras();
		userId = bundle.getString(Constent.USERID);
		name = bundle.getString(Constent.NAME);
		textView.setText(StringUtil.isEmpty(name) ? "用户" + userId.subSequence(userId.length() - 6, userId.length()) : name);
		questionId = bundle.getString(Constent.QUESTIONID);
		report = (RelativeLayout) findViewById(R.id.report);
		replyStatus = bundle.getInt("replyStatus");
		back_btn = (ImageButton) findViewById(R.id.back_btn);
		orenge_btn = (ImageButton) findViewById(R.id.orenge_btn);
		orenge_btn.setVisibility(View.VISIBLE);
		orenge_btn.setImageResource(R.drawable.more);
		soft_input_img = (ImageView) findViewById(R.id.soft_input_img);
		voice_input_img = (ImageView) findViewById(R.id.voice_input_img);
		send_btn = (TextView) findViewById(R.id.send_btn);
		todo_text = (TextView) findViewById(R.id.todo_text);
		voice_img = (ImageView) findViewById(R.id.voice_img);
		publish_text = (EditText) findViewById(R.id.publish_text);
		bottom_layout = (RelativeLayout) findViewById(R.id.bottom_layout);
		voice_layout = (RelativeLayout) findViewById(R.id.voice_layout);
		question_layout = (RelativeLayout) findViewById(R.id.question_layout);
		close = (RelativeLayout) findViewById(R.id.close);
		card = (RelativeLayout) findViewById(R.id.card);
		custom_list = (PullToCustomListView) findViewById(R.id.custom_list);
		select_dialog = (LinearLayout) findViewById(R.id.select_dialog);
		full_screem = (LinearLayout) findViewById(R.id.full_screem);
		custom_list.setPullToRefreshEnabled(false);
		listView = custom_list.getRefreshableView();
		todo_text.setText("按住说话");
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(ACTION);
		myIntentFilter.addAction(DIALOG_DOCTOR_EVALUATE);
		registerReceiver(questionReceiver, myIntentFilter);
		if (replyStatus == 3) {
			bottom_layout.setVisibility(View.GONE);
		}
		if (SharedPreferencesDB.getInstance(this).getIsFirst() && replyStatus == 2)
			popupHandler.sendEmptyMessageDelayed(0, 1000);
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	private void initPop(View parent) {
		DisplayMetrics dm = new DisplayMetrics();
		QuestionOnLineActivity.this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int height = dm.heightPixels;// 高度
		View view = (LinearLayout) LayoutInflater.from(QuestionOnLineActivity.this).inflate(R.layout.pop_noty, null);
		pop_noty = new PopupWindow(view, LayoutParams.MATCH_PARENT, height);
		more_noty = (LinearLayout) view.findViewById(R.id.more_noty);
		pop_noty.setContentView(view);
		pop_noty.setHeight(dm.heightPixels - QuestionOnLineActivity.this.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop());
		pop_noty.setFocusable(true);
		pop_noty.setAnimationStyle(R.style.AnimationFade);
		pop_noty.setBackgroundDrawable(new BitmapDrawable());
		more_noty.setOnClickListener(this);
		Rect frame = new Rect();
		QuestionOnLineActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		// 状态栏高度
		int statusBarHeight = frame.top;
		pop_noty.showAtLocation(parent, Gravity.TOP, 0, statusBarHeight);
	}

	@Override
	public int getResLayoutId() {

		return R.layout.activity_question_online;

	}

	@Override
	protected void onStart() {
		if (onLineTalkWithAdapter.getCount() < 1)
			postList();
		super.onStart();

	}

	/**
	 * <p>
	 * 功能 获取对话内容
	 * </p>
	 * 
	 * @author 皮勉 时间 2014年11月12日 上午11:44:07
	 */
	private void postList() {
		LogUtils.e("====postList======QuestionOnLineActivity=============");
		Intent intentService = new Intent(DialogueService.ACTION_INIT);
		Bundle bundleService = new Bundle();
		DialogueBeen dialogueBeen = new DialogueBeen();
		dialogueBeen.questionId = questionId;
		bundleService.putSerializable("DialogueBeen", dialogueBeen);
		intentService.putExtras(bundleService);
		sendBroadcast(intentService);
	}

	@Override
	public void onClick(View v) {
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		switch (v.getId()) {
		case R.id.back_btn:
			finish();
			break;
		case R.id.more_noty:
			SharedPreferencesDB.getInstance(this).setIsFirst(false);
			pop_noty.dismiss();
			break;
		case R.id.orenge_btn:
			if (replyStatus != 2) {
				close.setVisibility(View.GONE);
			} else {
				close.setVisibility(View.VISIBLE);
			}
			if (select_dialog.getVisibility() == View.VISIBLE) {
				select_dialog.setVisibility(View.GONE);
			} else {
				select_dialog.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.soft_input_img:
			select_dialog.setVisibility(View.GONE);
			send_btn.setVisibility(View.VISIBLE);
			publish_text.setVisibility(View.VISIBLE);
			voice_input_img.setVisibility(View.VISIBLE);
			soft_input_img.setVisibility(View.GONE);
			voice_layout.setVisibility(View.GONE);
			break;
		case R.id.voice_input_img:
			select_dialog.setVisibility(View.GONE);
			send_btn.setVisibility(View.GONE);
			publish_text.setVisibility(View.GONE);
			soft_input_img.setVisibility(View.VISIBLE);
			voice_input_img.setVisibility(View.GONE);
			voice_layout.setVisibility(View.VISIBLE);
			break;
		case R.id.send_btn:
			select_dialog.setVisibility(View.GONE);
			if (StringUtil.isEmpty(publish_text.getText().toString())) {
				Toast.makeText(QuestionOnLineActivity.this, "内容不能为空", Toast.LENGTH_SHORT).show();
				return;
			}
			Intent intentService = new Intent(DialogueService.ACTION);
			Bundle bundleService = new Bundle();
			DialogueBeen dialogueBeen = new DialogueBeen();
			dialogueBeen.questionId = questionId;
			dialogueBeen.text = publish_text.getText().toString();
			bundleService.putSerializable("DialogueBeen", dialogueBeen);
			intentService.putExtras(bundleService);
			sendBroadcast(intentService);
			break;
		case R.id.card:
			select_dialog.setVisibility(View.GONE);
			Intent intent = new Intent(QuestionOnLineActivity.this, SickDetailActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString(Constent.USERID, userId);
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		case R.id.report:
			select_dialog.setVisibility(View.GONE);
			Intent intentRport = new Intent(QuestionOnLineActivity.this, PostReportActivity.class);
			intentRport.putExtra("questionId", questionId);
			startActivity(intentRport);

			break;
		case R.id.close:
			select_dialog.setVisibility(View.GONE);
			SureCanclePop sureCanclePop = new SureCanclePop(QuestionOnLineActivity.this, resources.getString(R.string.sure_close));
			sureCanclePop.setWindflowerDelegate(new WindflowerDelegate() {

				@Override
				public void setName(String name) {

				}

				@Override
				public void setId(String _id) {

				}

				@Override
				public void isOr(boolean bool) {
					if (bool) {
						Intent intentService = new Intent(DialogueService.ACTION_CLOSE);
						Bundle bundleService = new Bundle();
						DialogueBeen dialogueBeen = new DialogueBeen();
						dialogueBeen.questionId = questionId;
						bundleService.putSerializable("DialogueBeen", dialogueBeen);
						intentService.putExtras(bundleService);
						sendBroadcast(intentService);
					}
				}
			});
			sureCanclePop.show();
			break;
		}
	}

	// 删除老文件
	void scanOldFile() {
		File file = new File(Environment.getExternalStorageState(), "my/voice.amr");
		if (file.exists()) {
			file.delete();
		}
	}

	// 录音时显示Dialog
	void showVoiceDialog() {
		dialog = new Dialog(QuestionOnLineActivity.this, R.style.DialogStyle);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		dialog.setContentView(R.layout.my_dialog);
		dialog_img = (ImageView) dialog.findViewById(R.id.dialog_img);
		time_text = (TextView) dialog.findViewById(R.id.time_text);
		dialog.show();
	}

	// 录音时显示Dialog
	void showVoiceCancleDialog() {
		dialogCancle = new Dialog(QuestionOnLineActivity.this, R.style.DialogStyle);
		dialogCancle.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogCancle.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		LinearLayout linearLayout = new LinearLayout(QuestionOnLineActivity.this);
		LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		linearLayout.setGravity(Gravity.CENTER);// 内容居中
		linearLayout.setBackgroundResource(R.drawable.cancle_send);
		dialogCancle.addContentView(linearLayout, layoutParams);
		dialogCancle.show();
	}

	// 录音时间太短时Toast显示
	void showWarnToast() {
		Toast toast = new Toast(QuestionOnLineActivity.this);
		LinearLayout linearLayout = new LinearLayout(QuestionOnLineActivity.this);
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		linearLayout.setPadding(20, 20, 20, 20);

		// 定义一个ImageView
		ImageView imageView = new ImageView(QuestionOnLineActivity.this);
		imageView.setImageResource(R.drawable.voice_to_short); // 图标

		TextView mTv = new TextView(QuestionOnLineActivity.this);
		mTv.setText("时间太短   录音失败");
		mTv.setTextSize(14);
		mTv.setTextColor(Color.WHITE);// 字体颜色
		// mTv.setPadding(0, 10, 0, 0);

		// 将ImageView和ToastView合并到Layout中
		linearLayout.addView(imageView);
		linearLayout.addView(mTv);
		linearLayout.setGravity(Gravity.CENTER);// 内容居中
		linearLayout.setBackgroundResource(R.drawable.record_bg);// 设置自定义toast的背景
		toast.setView(linearLayout);
		toast.setGravity(Gravity.CENTER, 0, 0);// 起点位置为中间 100为向下移100dp
		toast.show();
	}

	// 获取文件手机路径
	private String getAmrPath() {
		File file = new File(Environment.getExternalStorageDirectory(), "my/voice.amr");
		return file.getAbsolutePath();
	}

	// 录音计时线程
	void mythread() {
		recordThread = new Thread(ImgThread);
		recordThread.start();
	}

	// 录音Dialog图片随声音大小切换
	void setDialogImage() {
		time_text.setText((int) recodeTime + "");
		LogUtils.e("===============setDialogImage==================" + voiceValue);
		if (voiceValue < 200.0) {
			dialog_img.setImageResource(R.drawable.record_animate_01);
		} else if (voiceValue > 200.0 && voiceValue < 800.0) {
			dialog_img.setImageResource(R.drawable.record_animate_02);
		} else if (voiceValue > 800.0 && voiceValue < 1600.0) {
			dialog_img.setImageResource(R.drawable.record_animate_03);
		} else if (voiceValue > 1600.0 && voiceValue < 3200.0) {
			dialog_img.setImageResource(R.drawable.record_animate_04);
		} else if (voiceValue > 3200.0 && voiceValue < 5000.0) {
			dialog_img.setImageResource(R.drawable.record_animate_05);
		} else if (voiceValue > 5000.0 && voiceValue < 8000.0) {
			dialog_img.setImageResource(R.drawable.record_animate_06);
		} else if (voiceValue > 8000.0) {
			dialog_img.setImageResource(R.drawable.record_animate_07);
		}

	}

	// 录音线程
	private Runnable ImgThread = new Runnable() {

		@Override
		public void run() {
			recodeTime = 0.0f;
			while (RECODE_STATE == RECORD_ING) {
				if (recodeTime >= MAX_TIME && MAX_TIME != 0) {
					imgHandle.sendEmptyMessage(0);
				} else {
					try {
						Thread.sleep(100);
						recodeTime += 0.1;
						if (RECODE_STATE == RECORD_ING) {
							voiceValue = mr.getAmplitude();

							imgHandle.sendEmptyMessage(1);
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}

		Handler imgHandle = new Handler() {
			@Override
			public void handleMessage(Message msg) {

				switch (msg.what) {
				case 0:
					// 录音超过60秒自动停止
					if (RECODE_STATE == RECORD_ING) {
						RECODE_STATE = RECODE_ED;
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
						try {
							mr.stop();
							voiceValue = 0.0;
						} catch (IOException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();

						}

						if (recodeTime < MIX_TIME) {
							showWarnToast();
							// record.setText("按住开始录音");
							RECODE_STATE = RECORD_NO;
						} else {
							imageAsyn = new UpLoadImageAsyn();
							imageAsyn.execute();
						}
					}
					break;
				case 1:
					setDialogImage();
					break;
				default:
					break;
				}

			}
		};
	};

	private QuestionReceiver questionReceiver = new QuestionReceiver();

	class QuestionReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent date) {
			if (date.getAction().equals(ACTION)) {
				boolean isInit = date.getExtras().getBoolean("INIT");
				DialogueBeen dialogueBeen = (DialogueBeen) date.getExtras().getSerializable("DialogueBeen");
				if (!isInit) {
					replyStatus = 2;
					close.setVisibility(View.VISIBLE);
					List<DialogueBeen> dialogueBeens = new ArrayList<DialogueBeen>();
					dialogueBeens.add(dialogueBeen);
					onLineTalkWithAdapter.addListData(dialogueBeens);
				} else {
					onLineTalkWithAdapter.addListData(dialogueBeen.sessionLogs);
				}
				if (onLineTalkWithAdapter.getCount() > 0)
					listView.setSelection(onLineTalkWithAdapter.getCount());
				publish_text.setText("");
			} else if (date.getAction().equals(DIALOG_DOCTOR_NEW_MESSAGE)) {
				// Toast.makeText(QuestionOnLineActivity.this, "用户向医生追问",
				// Toast.LENGTH_SHORT).show();
			} else if (date.getAction().equals(DIALOG_DOCTOR_EVALUATE)) {
				replyStatus = 3;
				bottom_layout.setVisibility(View.GONE);
				DialogueBeen dialogueBeen = (DialogueBeen) date.getExtras().getSerializable("DialogueBeen");
				List<DialogueBeen> dialogueBeens = new ArrayList<DialogueBeen>();
				dialogueBeens.add(dialogueBeen);
				onLineTalkWithAdapter.addListData(dialogueBeens);
			}
		}
	}

	@Override
	protected void onDestroy() {
		if (imageAsyn != null)
			imageAsyn.cancel(true);
		unregisterReceiver(questionReceiver);
		onLineTalkWithAdapter.stopAudio();
		super.onDestroy();

	}

	class UpLoadImageAsyn extends AsyncTask<Object, Void, String> {

		@Override
		protected String doInBackground(Object... arg0) {

			return uploadFile(AUDIO_UPLOAD_URL, getAmrPath(), QuestionOnLineActivity.this, null);
		}

		@Override
		protected void onPostExecute(String result) {
			if (!StringUtil.isEmpty(result)) {
				String url = getFileName(result);
				if (!StringUtil.isEmpty(url) && url.contains("http")) {
					Intent intentService = new Intent(DialogueService.ACTION);
					Bundle bundleService = new Bundle();
					DialogueBeen dialogueBeen = new DialogueBeen();
					dialogueBeen.questionId = questionId;
					dialogueBeen.audio = url;
					dialogueBeen.size = ((int) recodeTime) + "";
					bundleService.putSerializable("DialogueBeen", dialogueBeen);
					intentService.putExtras(bundleService);
					sendBroadcast(intentService);
				} else {
					Toast.makeText(QuestionOnLineActivity.this, "语音上传失败", Toast.LENGTH_SHORT).show();
				}
			}
			super.onPostExecute(result);
		}
	}

	public static String uploadFile(String actionUrl, String uploadFile, Context context, String parameter) {
		HttpURLConnection con = null;
		InputStream is = null;
		DataOutputStream ds = null;
		FileInputStream fStream = null;
		actionUrl = actionUrl + "?" + parameter;// "http://img.mobile.fengxz.com.cn/upload"
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String fileName = "";
		Log.e("======uploadFile======", uploadFile);
		if (uploadFile != null && uploadFile.lastIndexOf(File.separator) > -1)
			fileName = uploadFile.substring(uploadFile.lastIndexOf(File.separator) + 1);
		File file = new File(uploadFile);
		if (file.exists()) {
			Log.e("======uploadFile======", "文件存在");
		} else {
			Log.e("======uploadFile======", "文件不存在");
		}
		try {
			URL url = new URL(actionUrl);
			con = getNewHttpURLConnection(url, context);

			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			con.setRequestMethod("POST");
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\";filename=\"" + fileName + "\"" + end);
			ds.writeBytes(end);

			fStream = new FileInputStream(file);
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];

			int length = -1;
			while ((length = fStream.read(buffer)) != -1) {
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			con.connect();
			is = con.getInputStream();
			String jsonStr = convertStreamToString(is);
			Log.e("===jsonStr====", jsonStr);
			return jsonStr;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return CONNECTION_FAIL;
		} catch (SocketTimeoutException e) {
			return CONNECTION_FAIL;
		} catch (IOException e) {
			e.printStackTrace();
			return CONNECTION_FAIL;
		} catch (Exception e) {
			return "上传失败";
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (fStream != null) {
					fStream.close();
				}
				if (ds != null) {
					ds.flush();
					ds.close();
				}
				if (con != null) {
					con.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	public static HttpURLConnection getNewHttpURLConnection(URL url, Context context) {
		HttpURLConnection connection = null;
		Cursor mCursor = null;
		try {
			connection = (HttpURLConnection) url.openConnection();
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			if (!wifiManager.isWifiEnabled()) {
				// 获取当前正在使用的APN接入点
				Uri uri = Uri.parse("content://telephony/carriers/preferapn");
				mCursor = context.getContentResolver().query(uri, null, null, null, null);
				if (mCursor != null && mCursor.moveToFirst()) {
					// 游标移至第一条记录，当然也只有一条
					String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
					if (proxyStr != null && proxyStr.trim().length() > 0) {
						Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxyStr, 80));
						connection = (HttpURLConnection) url.openConnection(proxy);
					}
				}
			}
			return connection;
		} catch (Exception e) {
			e.printStackTrace();
			try {
				return (HttpURLConnection) url.openConnection();
			} catch (IOException e1) {
				e1.printStackTrace();
				return null;
			}
		} finally {
			if (mCursor != null) {
				mCursor.close();
			}
		}

	}

	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8 * 1024);
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
		} finally {
			try {
				is.close();
			} catch (IOException e) {
			}
		}

		return sb.toString();
	}

	public static String getFileName(String jsonStr) {
		if (!StringUtil.isEmpty(jsonStr) && jsonStr.contains("files")) {
			String newJson = jsonStr.substring(jsonStr.indexOf(":") + 1);
			try {
				JSONArray jsonArray = new JSONArray(newJson);
				for (int i = 0, p = jsonArray.length(); i < p; i++) {
					JSONObject jsonObject = jsonArray.optJSONObject(i);
					if (StringUtil.isEmpty(jsonObject.optString("error")))
						return jsonObject.optString("url");
					return null;
				}

			} catch (JSONException e1) {
				e1.printStackTrace();
				return null;
			}
		}
		return null;
	}

}
